###from QQmail To 163mail
import poplib
from email.parser import Parser
##from email.utils import parseaddr
from email.header import decode_header 
import base64

mail_addr = '***@163.com'
mail_pwd = '***'

pop_server = 'pop3.163.com'

def receivemail():
    server = poplib.POP3(pop_server)
##    server.set_debuglevel(1)
    print(server.getwelcome().decode('utf-8'))
    server.user(mail_addr)
    server.pass_(mail_pwd)
    print('message: %s.Size:%s'%server.stat()) #占用空间
    resp,mails,octets = server.list() #邮件编号
##    print(mails)
    index = len(mails)
    resp,lines,octets = server.retr(index) #最新一封邮件
    content = b'\r\n'.join(lines).decode('utf-8')
    msg=Parser().parsestr(content)
##    print(msg)
    senduser=msg.get('From')
    reuser=msg.get('To')
    title=msg.get('Subject')

    senduser=dcode_str(senduser,1)+(decode_header(senduser)[2][0]).decode('utf-8').strip('"').strip()
    print('发件人：{}'.format(senduser))
    reuser=dcode_str(reuser,1)+(decode_header(reuser)[2][0]).decode('utf-8').strip('"').strip()
    print('接收人：{}'.format(reuser))
    print('主题：{}'.format(dcode_str(title,0)))
    if (msg.is_multipart()):
        parts=msg.get_payload()
        for n,part in enumerate(parts):
##            print(n,part)
    
            con_type=part.get_content_type()
##            print(con_type)
            cont_charset=part.get_content_charset()
            if con_type=='text/plain' or con_type=='text/html':
                print(decode_base64(part.get_payload()).decode(cont_charset))

            elif con_type=='multipart/alternative': #带图片
                cont=part.get_payload()
                for a in cont:
                    c=a.get_content_charset()
                    print(decode_base64(a.get_payload()).decode(c))
            elif con_type=='application/octet-stream': #附件
                c=part.get_content_charset()
                print('附件：')
                print(decode_base64(part.get_filename()).decode(c))
                 
            #print(type(part.get_payload()))       
   
    '''       
    else:
        cont_type=msg.get_content_type()
        if cont_type=='text/plain' or cont_type=='text/html':
            cont=msg.get_payload(decode=True)
            print(cont)
        else:
            print(comt_type) #附件
    '''

    server.quit()

def dcode_str(s,i):
    value,charset=decode_header(s)[i]
    if charset:
        value=value.decode(charset)
    return value

    
def decode_base64(st):
    missing_padding = 4 - len(st) % 4
    if missing_padding:
        st += '='* missing_padding
    return base64.b64decode(st)
    


if __name__=='__main__':
    receivemail()
